﻿using System.IO;
using System.Runtime.InteropServices.Marshalling;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Serialization;

namespace d1
{
    public class Order
    {
        public int OrderId { get; set; }
        public string Customer { get; set; }
        public decimal TotalAmount
        {
            get { return Details.Sum(item => item.Amount); }
        }

        //一个订单中包含多个货物的订单详情
        public List<OrderDetails> Details { get; set; } = new List<OrderDetails>();

        //初始化
        public Order() { }
        public Order(int orderId, string customer)
        {
            OrderId = orderId;
            Customer = customer;
        }

        //重写Equals
        public override bool Equals(object? obj)
        {
            if (obj == null || !(obj is Order)) return false;

            Order other = (Order)obj;
            return this.OrderId == other.OrderId;
        }

        public override int GetHashCode()
        {
            return OrderId.GetHashCode();
        }

        //添加订单的详细信息
        public void AddDetail(OrderDetails detail)
        {
            if (!Equals(detail))
            {
                Details.Add(detail);
            }
        }

        //重写ToString方法，方便打印
        public override string ToString()
        {
            return $"订单号:{this.OrderId}, 客户：{Customer}, 总金额：{this.TotalAmount}\n"
                + string.Join("\n", Details.Select(d => $" - {d}"));
        }

        //删除订单明细,根据货物类型删除订单
        public bool Remove(string product)
        {
            var detail = Details.FirstOrDefault(d => d.ProductName == product);
            if (detail != null)
            {
                return false;
            }
            else
            {
                return Details.Remove(detail);
            }
        }
    }

    public class OrderDetails
    {
        //货物种类，货物数量，货物单价，总价
        public string ProductName { get; set; }
        public decimal UnitPrice { get; set; }
        public int Quantity { get; set; }
        public decimal Amount
        {
            get { return UnitPrice * Quantity; }
        }

        public OrderDetails() { }
        public OrderDetails(string productName, decimal unitPrice, int quantity)
        {
            this.ProductName = productName;
            this.UnitPrice = unitPrice;
            this.Quantity = quantity;
        }

        public override string ToString()
        {
            return $"{ProductName} ×{Quantity} 单价: {UnitPrice:C}, 小计: {Amount:C}";
        }

        public override bool Equals(object? obj)
        {
            return obj is OrderDetails other && ProductName == other.ProductName;
        }

        public override int GetHashCode()
        {
            return ProductName.GetHashCode();
        }
    }

    public class OrderService
    {
        public List<Order> Orders = new List<Order>();

        //添加订单
        public void AddOrder(Order order)
        {
            if (Orders.Contains(order))
            {
                throw new ArgumentException($"订单{order.OrderId}已存在！");
            }
            else
            {
                Orders.Add(order);
            }
        }

        //根据id删除订单
        public void RemoveOrder(int OrderId)
        {
            var order = Orders.FirstOrDefault(o => o.OrderId == OrderId);
            if (order == null)
            {
                throw new ArgumentNullException($"订单不存在");
            }
            else
            {
                Orders.Remove(order);
            }
        }

        //修改订单
        public bool UpdateOrder(Order newOrder)
        {
            var index = Orders.FindIndex(o => o.Equals(newOrder));
            if (index < 0)
            {
                Console.WriteLine("订单修改失败");
                return false;
            }
            Orders[index] = newOrder;
            return true;
        }

        //输出全部订单
        public List<Order> GetAllOrders()
        {
            var query = Orders.AsQueryable();
            return query.OrderBy(o => o.TotalAmount).ToList();
        }
        public void DisplayAllOrders() =>
        Console.WriteLine(string.Join("\n\n", Orders));
        //订单查询功能
        public List<Order> GetOrdersByCustomer(string customer)
        {
            var query = Orders.Where(o => o.Customer.Contains(customer));
            return query.OrderBy(o => o.TotalAmount).ToList();
        }

        public List<Order> GerOrdersById(int id)
        {
            var query = Orders.Where(o => o.OrderId == id);
            return query.OrderBy(o => o.TotalAmount).ToList();
        }

        public List<Order> GetOrdersByProduct(string productName)
        {
            var query = Orders.Where(o => o.Details.Any(d => d.ProductName.Contains(productName)));
            return query.OrderBy(o => o.TotalAmount).ToList();
        }

        public List<Order> GerOrdersByAmount(decimal amount)
        {
            var query = Orders.Where(o => o.TotalAmount == amount);
            return query.OrderBy(o => o.TotalAmount).ToList();
        }

        public void Export(string fileName)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
            using (FileStream fs = new FileStream(fileName, FileMode.Create))
            {
                serializer.Serialize(fs, Orders);
            }
        }

        public void Import(string fileName)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Order>));
            using (FileStream fs = new FileStream(fileName, FileMode.Open))
            {
                List<Order>? importedOrders = serializer.Deserialize(fs) as List<Order>;
                if (importedOrders != null)
                {
                    Orders = importedOrders;
                }
                else { Console.WriteLine("导入失败"); }
            }
        }
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            OrderService orderService = new OrderService();

            try
            {
                Console.WriteLine("=== 添加订单 ===");
                Order order1 = new Order(1, "张三");
                order1.AddDetail(new OrderDetails("手机", 5999m, 1));
                order1.AddDetail(new OrderDetails("耳机", 199m, 2));
                orderService.AddOrder(order1);
                Console.WriteLine("订单1添加成功");

                Order order2 = new Order(2, "李四");
                order2.AddDetail(new OrderDetails("笔记本电脑", 8999m, 1));
                orderService.AddOrder(order2);
                Console.WriteLine("订单2添加成功");

                // 尝试重复添加
                try
                {
                    orderService.AddOrder(order1);
                }
                catch (ArgumentException e)
                {
                    Console.WriteLine($"预期异常：{e.Message}");
                }

                Console.WriteLine("\n=== 当前所有订单 ===");
                orderService.DisplayAllOrders();

                Console.WriteLine("\n=== 查询订单 ===");
                Console.WriteLine("\n客户包含“张”的订单：");
                orderService.GetOrdersByCustomer("张").ForEach(Console.WriteLine);

                Console.WriteLine("\n包含商品“手机”的订单：");
                orderService.GetOrdersByProduct("手机").ForEach(Console.WriteLine);

                Console.WriteLine("\n订单 ID 为 2 的订单：");
                orderService.GerOrdersById(2).ForEach(Console.WriteLine);

                Console.WriteLine("\n总金额为 6397 的订单：");
                orderService.GerOrdersByAmount(6397m).ForEach(Console.WriteLine);

                Console.WriteLine("\n=== 修改订单 ===");
                Order modifiedOrder = new Order(1, "张三（VIP）");
                modifiedOrder.AddDetail(new OrderDetails("手机", 5999m, 1));
                modifiedOrder.AddDetail(new OrderDetails("充电宝", 129m, 1));
                if (orderService.UpdateOrder(modifiedOrder))
                {
                    Console.WriteLine("订单修改成功");
                }

                Console.WriteLine("\n修改后的订单1：");
                orderService.GerOrdersById(1).ForEach(Console.WriteLine);

                Console.WriteLine("\n=== 删除订单 ===");
                orderService.RemoveOrder(2);
                Console.WriteLine("删除订单2成功");

                try
                {
                    orderService.RemoveOrder(99);
                }
                catch (ArgumentNullException e)
                {
                    Console.WriteLine($"预期异常：{e.Message}");
                }

                Console.WriteLine("\n当前所有订单：");
                orderService.DisplayAllOrders();

                Console.WriteLine("\n=== 导出订单到 XML ===");
                orderService.Export("orders_test.xml");

                Console.WriteLine("\n=== 清空订单并从 XML 导入 ===");
                orderService = new OrderService(); // 新建，模拟空列表
                orderService.Import("orders_test.xml");

                Console.WriteLine("导入后的订单列表：");
                orderService.DisplayAllOrders();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"未预期的异常：{ex.Message}");
            }
        }
    }
}


